/**
 * This file is part of the DbUnit module for NetBeans IDE
 * Copyright (C) 2009 Pavol Pitoňák
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

package cz.muni.fi.dbunit;

import java.awt.Component;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.project.JavaProjectConstants;
import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.api.project.libraries.Library;
import org.netbeans.api.project.libraries.LibraryManager;
import org.netbeans.spi.java.project.support.ui.templates.JavaTemplates;
import org.netbeans.spi.project.ui.templates.support.Templates;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataFolder;
import org.openide.loaders.DataObject;

/**
 *
 * @author Pavol Pitoňák <pavol@pitonak.com>
 */
public final class DataSetGeneratorWizardIterator implements WizardDescriptor.InstantiatingIterator {

    private int index;
    private WizardDescriptor wizard;
    private WizardDescriptor.Panel[] panels;

    /**
     * Initialize panels representing individual wizard's steps and sets
     * various properties for them influencing wizard appearance.
     */
    private WizardDescriptor.Panel[] getPanels() {
        if (panels == null) {
            Project project = Templates.getProject(wizard);
            Sources sources = project.getLookup().lookup(Sources.class);
            SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);

            // we want only test directories
            for (int i = 0; i < groups.length; i++) {
                if ("${src.dir}".equals(groups[i].getName())) {
                    groups = new SourceGroup[]{groups[i]};
                    break;
                }
            }

            panels = new WizardDescriptor.Panel[]{
                        JavaTemplates.createPackageChooser(project, groups, new DataSetGeneratorWizardPanel()),
                    };
            String[] steps = createSteps();
            for (int i = 0; i < panels.length; i++) {
                Component c = panels[i].getComponent();
                if (steps[i] == null) {
                    // Default step name to component name of panel. Mainly
                    // useful for getting the name of the target chooser to
                    // appear in the list of steps.
                    steps[i] = c.getName();
                }
                if (c instanceof JComponent) { // assume Swing components
                    JComponent jc = (JComponent) c;
                    // Sets step number of a component
                    // TODO if using org.openide.dialogs >= 7.8, can use WizardDescriptor.PROP_*:
                    jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer(i));
                    // Sets steps names for a panel
                    jc.putClientProperty("WizardPanel_contentData", steps);
                    // Turn on subtitle creation on each step
                    jc.putClientProperty("WizardPanel_autoWizardStyle", Boolean.TRUE);
                    // Show steps on the left side with the image on the background
                    jc.putClientProperty("WizardPanel_contentDisplayed", Boolean.TRUE);
                    // Turn on numbering of all steps
                    jc.putClientProperty("WizardPanel_contentNumbered", Boolean.TRUE);
                }
            }
        }
        return panels;
    }

    @Override
    public Set instantiate() throws IOException {
        // prepare the arguments for passing to the FreeMarker template
        Map<String, Object> args = prepareArgsForFreeMarker();

        // get the template and convert it
        FileObject template = Templates.getTemplate(wizard);
        DataObject dTemplate = DataObject.find(template);

        // get the package
        FileObject dir = Templates.getTargetFolder(wizard);
        DataFolder df = DataFolder.findFolder(dir);

        // get the class
        String targetName = Templates.getTargetName(wizard);


        // define the template from the above
        // pass the package, the file name, and the map of strings to the template
        DataObject dobj = dTemplate.createFromTemplate(df, targetName, args);

        // obtain a FileObject
        FileObject createdFile = dobj.getPrimaryFile();

        // add DbUnit to classpath
        Library[] libs = new Library[] {LibraryManager.getDefault().getLibrary("DbUnit")};
        if (libs != null) {
            ProjectClassPathModifier.addLibraries(libs, createdFile, ClassPath.COMPILE);
        }
        
        return Collections.singleton(createdFile);
    }

    @Override
    public void initialize(WizardDescriptor wizard) {
        this.wizard = wizard;
    }

    @Override
    public void uninitialize(WizardDescriptor wizard) {
        panels = null;
    }

    @Override
    public WizardDescriptor.Panel current() {
        return getPanels()[index];
    }

    @Override
    public String name() {
        return index + 1 + ". from " + getPanels().length;
    }

    @Override
    public boolean hasNext() {
        return index < getPanels().length - 1;
    }

    @Override
    public boolean hasPrevious() {
        return index > 0;
    }

    @Override
    public void nextPanel() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        index++;
    }

    @Override
    public void previousPanel() {
        if (!hasPrevious()) {
            throw new NoSuchElementException();
        }
        index--;
    }

    // If nothing unusual changes in the middle of the wizard, simply:
    @Override
    public void addChangeListener(ChangeListener l) {
    }

    @Override
    public void removeChangeListener(ChangeListener l) {
    }

    // You could safely ignore this method. Is is here to keep steps which were
    // there before this wizard was instantiated. It should be better handled
    // by NetBeans Wizard API itself rather than needed to be implemented by a
    // client code.
    private String[] createSteps() {
        String[] beforeSteps = null;
        Object prop = wizard.getProperty("WizardPanel_contentData");
        if (prop != null && prop instanceof String[]) {
            beforeSteps = (String[]) prop;
        }

        if (beforeSteps == null) {
            beforeSteps = new String[0];
        }

        String[] res = new String[(beforeSteps.length - 1) + panels.length];
        for (int i = 0; i < res.length; i++) {
            if (i < (beforeSteps.length - 1)) {
                res[i] = beforeSteps[i];
            } else {
                res[i] = panels[i - beforeSteps.length + 1].getComponent().getName();
            }
        }
        return res;
    }

    private Map<String, Object> prepareArgsForFreeMarker() {
        Map<String, Object> args = new HashMap<String, Object>();
        String tmpString;
        
        tmpString = (String) wizard.getProperty(DataSetGeneratorVisualPanel.DATABASE_URL);
        if (tmpString != null) {
            args.put("databaseUrl", tmpString);
        }

        tmpString = (String) wizard.getProperty(DataSetGeneratorVisualPanel.DATABASE_USERNAME);
        if (tmpString != null) {
            args.put("databaseUsername", tmpString);
        }

        tmpString = (String) wizard.getProperty(DataSetGeneratorVisualPanel.DATABASE_PASSWD);
        if (tmpString != null) {
            args.put("databasePassword", tmpString);
        }

        tmpString = (String) wizard.getProperty(DataSetGeneratorVisualPanel.DATABASE_SCHEMA);
        if (tmpString != null) {
            args.put("databaseSchema", tmpString);
        }

        return args;
    }
}
